/**
 * Created by wust on 2019-10-21 14:37:36
 * Copyright © 2019 wust. All rights reserved.
 */
package com.sc.admin.core.api.web;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.sc.admin.core.bo.NotificationBo;
import com.sc.admin.core.service.SysMyNoticeService;
import com.sc.admin.core.service.SysNotificationTimelineService;
import com.sc.admin.core.service.SysUserOrganizationService;
import com.sc.common.annotations.OperationLog;
import com.sc.common.annotations.WebApi;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.dto.PageDto;
import com.sc.common.dto.WebResponseDto;
import com.sc.common.entity.admin.mynotice.SysMyNotice;
import com.sc.common.entity.admin.mynotice.SysMyNoticeList;
import com.sc.common.entity.admin.mynotice.SysMyNoticeSearch;
import com.sc.common.entity.admin.notification.SysNotificationTimeline;
import com.sc.common.enums.OperationLogEnum;
import com.sc.common.util.cache.DataDictionaryUtil;
import com.sc.mq.producer.Producer4routingKey;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;

/**
 * @author: wust
 * @date: Created in 2019-10-21 14:37:36
 * @description: 我的通知
 *
 */
@WebApi
@RequestMapping("/web/v1/MyNoticeController")
@RestController
public class MyNoticeController {
    @Autowired
    private SysMyNoticeService sysMyNoticeServiceImpl;

    @Autowired
    private SysUserOrganizationService sysUserOrganizationServiceImpl;

    @Autowired
    private SysNotificationTimelineService sysNotificationTimelineServiceImpl;

    @Autowired
    private Producer4routingKey producer4routingKey;

    @Autowired
    private NotificationBo notificationBo;

    @Autowired
    private Environment env;

    @OperationLog(moduleName= OperationLogEnum.MODULE_ADMIN_NOTIFICATION,businessName="分页查询",operationType= OperationLogEnum.Search)
    @RequestMapping(value = "/listPage",method = RequestMethod.POST)
    public WebResponseDto listPage(@RequestBody SysMyNoticeSearch search){
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        WebResponseDto responseDto = new WebResponseDto();

        search.setReceiver(ctx.getAccountId());

        PageDto pageDto = search.getPageDto();
        List<SysMyNoticeList> list =  sysMyNoticeServiceImpl.selectByPageNumSize(search,pageDto.getPageNum(),pageDto.getPageSize()) == null ? null
                : (List<SysMyNoticeList>)sysMyNoticeServiceImpl.selectByPageNumSize(search,pageDto.getPageNum(),pageDto.getPageSize());
        if(CollectionUtils.isNotEmpty(list)){
            for (SysMyNoticeList myNoticeList : list) {
                myNoticeList.setStatusLabel(DataDictionaryUtil.getLookupNameByCode(ctx.getLocale().toString(),myNoticeList.getStatus()));
            }
        }
        PageInfo page = new PageInfo(list);
        BeanUtils.copyProperties(page,pageDto);
        responseDto.setPage(pageDto);
        responseDto.setLstDto(list);
        return responseDto;
    }



    @RequestMapping(value = "/detail/{notificationId}",method = RequestMethod.POST)
    public WebResponseDto detail(@PathVariable Long notificationId){
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        SysMyNotice myNoticeSearch = new SysMyNotice();
        myNoticeSearch.setNotificationId(notificationId);
        myNoticeSearch.setReceiver(ctx.getAccountId());
        SysMyNotice sysMyNotice = sysMyNoticeServiceImpl.selectOne(myNoticeSearch);
        if(sysMyNotice != null){
            if("A101502".equals(sysMyNotice.getStatus())){
                sysMyNotice.setStatus("A101501"); // 修改为已读
                sysMyNotice.setModifyId(ctx.getAccountId());
                sysMyNotice.setModifyName(ctx.getAccountName());
                sysMyNotice.setModifyTime(new Date());
                sysMyNoticeServiceImpl.updateByPrimaryKey(sysMyNotice);
            }


            /**
             * 获取报警记录时间线
             */
            Example example = new Example(SysNotificationTimeline.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("notificationId",notificationId);
            example.setOrderByClause("create_time DESC");
            List<SysNotificationTimeline> notificationTimelines = sysNotificationTimelineServiceImpl.selectByExample(example);
            if(CollectionUtil.isNotEmpty(notificationTimelines)){
                JSONArray jsonArray = new JSONArray();
                int i = notificationTimelines.size();
                for (SysNotificationTimeline notificationTimeline : notificationTimelines) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("timestamp", "第" + (i--) + "次  " + new DateTime(notificationTimeline.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
                    jsonObject.put("datetime", new DateTime(notificationTimeline.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
                    jsonObject.put("type",notificationTimeline.getType());
                    jsonObject.put("typeLabel",DataDictionaryUtil.getLookupNameByCode(ctx.getLocale().toString(),notificationTimeline.getType()));
                    jsonObject.put("description",notificationTimeline.getDescription());
                    jsonArray.add(jsonObject);
                }
                responseDto.setObj(jsonArray);
            }


            // 提醒监听者重新读取我的未读消息数量
            notificationBo.pushToMyNoticeQueue(null,"2");
        }
        return responseDto;
    }

    @OperationLog(moduleName= OperationLogEnum.MODULE_ADMIN_NOTIFICATION,businessName="删除我的消息",operationType= OperationLogEnum.Delete)
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public WebResponseDto delete(@PathVariable Long id) {
        WebResponseDto responseDto = new WebResponseDto();
        sysMyNoticeServiceImpl.deleteByPrimaryKey(id);
        return responseDto;
    }
}
